/**
 * Created with IntelliJ IDEA.
 * User: yanshiyi
 * Date: 13-12-2
 * Time: 下午8:41
 * To change this template use File | Settings | File Templates.
 */
package expression

import (
	C "collections"
	"strconv"
	"strings"
)

var operatorMap = map[string]func(a, b int64) int64{
	"+": add, "-": minus, "*": multiply, "/": divide,
}

func EvaluatePostfix(expression string) (result int64) {

	stack := new(C.ArrayStack)

	tokens := strings.Split(expression, " ")

	for _, token := range tokens {

		operator, ok := operatorMap[token]

		if ok {
			i := stack.Pop().(int64)
			j := stack.Pop().(int64)
			result = operator(i, j)
			stack.Push(result)
		} else {
			value, error := strconv.ParseInt(token, 0, 0)

			if error == nil {
				stack.Push(value)
			} else {
				panic(error)
			}
		}
	}
	return
}
